package com.pdool.game.server;

import com.pdool.game.constant.SessionAttr;
import com.pdool.game.mgr.UserMgr;
import com.pdool.game.msg.MsgTask;
import com.pdool.game.msg.UserMsgQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.BinaryWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

@Component
public class GameWebsocketServer extends BinaryWebSocketHandler {
    @Autowired
    ThreadPoolTaskExecutor logicThreadPool;


    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        System.out.println("连接成功" + session.getId());
        //  todo 登录操作
        UserMgr.getInstance().getSessionMap().put(session.getId(), session);
        System.out.println("当前在线人数：" + UserMgr.getInstance().getSessionMap().size());
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
        Map<String, Object> attributes = session.getAttributes();
        UserMsgQueue queue = (UserMsgQueue) attributes.computeIfAbsent(SessionAttr.MSG_QUEUE,(key)-> new UserMsgQueue(session, logicThreadPool));
        MsgTask msgTask = new MsgTask(session, message);
        queue.addQueue(msgTask);

    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接出错" + session.getId());
        if (!session.isOpen()) {
            UserMgr.getInstance().getSessionMap().remove(session.getId(), session);
            session.close();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("关闭连接" + session.getId());
        if (!session.isOpen()) {
            UserMgr.getInstance().getSessionMap().remove(session.getId(), session);
            System.out.println("当前在线人数：" + UserMgr.getInstance().getSessionMap().size());
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * sendMessageToUser:发给指定用户
     */
    public void sendMessageToUser(String userId, String contents) {
        WebSocketSession session = UserMgr.getInstance().getSessionMap().get(userId);
        if (session != null && session.isOpen()) {
            try {
                TextMessage message = new TextMessage(contents);
                session.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * sendMessageToAllUsers:发给所有的用户
     */
    public void sendMessageToAllUsers(String contents) {
        Set<String> userIds = UserMgr.getInstance().getSessionMap().keySet();
        for (String userId : userIds) {
            this.sendMessageToUser(userId, contents);
        }
    }
}